package com.asuna.video_website.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Service
public class MediaService {
    public void getVideo(String videoPath, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File file = new File(videoPath);
        if (!file.exists()) {
            response.setStatus(404);
            return;
        }

        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        long start = 0;
        long fileLength = file.length();
        FileInputStream ins = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(ins);
        String range = request.getHeader("Range");
        if (range != null && range.trim().length() > 0 && !range.equals("null")) {
            String rangBytes = range.replaceAll("bytes=", "");
            start = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
            bis.skip(start);
        }
        String contentLength = Long.toString(fileLength - start);
        //String contentLength = Long.toString(Math.min(100000,fileLength-start));
        //String end = Long.toString(Math.min(start+99999,fileLength-1));
        String contentRange = "bytes " + start + "-" + (fileLength - 1) + "/" + fileLength;
        //String contentRange = "bytes " + start + "-" + end + "/" + fileLength;
        response.reset();
        response.setStatus(206);
        response.setContentType("video/mp4");
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Range", contentRange);
        response.setHeader("Content-Length", contentLength);
        OutputStream out = response.getOutputStream();
        for (int l = bis.read(bytes); l != -1; l = bis.read(bytes)) {
            out.write(bytes);
        }
        out.flush();
        out.close();
    }

    public void uploadVideo(String uploadPath, MultipartFile file) throws IOException {
        File fatherFile = new File(uploadPath);
        if (!fatherFile.exists())
            if (!fatherFile.mkdirs()) {
                System.out.println("[error]目录创建失败：" + uploadPath);
                return;
            }
        File targetFile = new File(uploadPath + file.getOriginalFilename());
        file.transferTo(targetFile);
    }

    public List<Map<String, Object>> getAllSortName(String path) {
        File file = new File(path);
        String[] sortNames = file.list();
        if (sortNames == null) {
            System.out.println("[error]目录中没有任何文件：" + path);
            return null;
        }
        List<Map<String, Object>> re = new ArrayList<>();
        for (String name : sortNames) {
            Map<String, Object> el = new HashMap<>();
            el.put("name", name);
            File episodes = new File(path + name);
            el.put("episode", episodes.list());
            re.add(el);
        }
        return re;
    }
}
